<script setup lang="ts">
import { ref, watch } from 'vue'
import { useMessage } from 'naive-ui'
import type { FormInst, FormRules } from 'naive-ui'
import { loginService } from '@/apis/login'
import { useUserStore } from '@/stores'
import { useRules } from "@/hooks/useRules"
import { registerService } from "@/apis/user"

const message = useMessage()
const router = useRouter()
const userStore = useUserStore()
const commonRules = useRules()

// 响应式状态
const loading = ref(false)
const isRegister = ref(false)
const formLoginRef = ref<FormInst | null>(null)
const formRegisterRef = ref<FormInst | null>(null)

// 表单数据
const formValue = ref({
  userName: '',
  password: '',
  phone: ''
})

// 验证规则
const loginRule: FormRules = {
  userName: commonRules.required("请输入账号"),
  password: commonRules.required("请输入密码"),
}

const registerRule: FormRules = {
  ...loginRule,
  phone: commonRules.phone("请输入正确的手机号")
}

// 增强的表单重置方法
const resetForm = () => {
  // 重置响应式数据
  formValue.value = {
    userName: '',
    password: '',
    phone: ''
  }
}

// 监听注册状态变化
watch(isRegister, () => {
  resetForm()
})

// 登录处理
const handleLogin = async (e: MouseEvent) => {
  e.preventDefault()
  formLoginRef.value?.validate(async (errors) => {
    if (!errors) {
      loading.value = true
      try {
        const res = await loginService(formValue.value)
        userStore.setToken(res.data.data.tokenValue)
        message.success('登录成功')
        await router.push('/')
      } finally {
        loading.value = false
      }
    }
  })
}

// 注册处理
const handleRegister = async () => {
  formRegisterRef.value?.validate(async (errors) => {
    if (!errors) {
      loading.value = true
      try {
        await registerService(formValue.value)
        message.success('注册成功')
        isRegister.value = false
      } finally {
        loading.value = false
      }
    }
  })
}
</script>

<template>
  <div class="min-h-screen bg-white flex items-center justify-center p-4">
    <n-card class="w-full max-w-md rounded-xl shadow-sm hover:shadow-md transition-shadow">
      <!-- 切换按钮组 -->
      <div class="flex gap-4 mb-8">
        <n-button
          ghost
          size="large"
          class="flex-1 h-12 rounded-lg transition-all font-medium"
          :type="!isRegister ? 'primary' : 'default'"
          @click="isRegister = false"
        >
          登录
        </n-button>
        <n-button
          ghost
          size="large"
          class="flex-1 h-12 rounded-lg transition-all font-medium"
          :type="isRegister ? 'primary' : 'default'"
          @click="isRegister = true"
        >
          注册
        </n-button>
      </div>

      <!-- 表单区域 -->
      <transition name="fade-slide" mode="out-in">
        <!-- 登录表单 -->
        <n-form
          v-if="!isRegister"
          ref="formLoginRef"
          :model="formValue"
          :rules="loginRule"
          class="space-y-6"
          key="login"
        >
          <n-form-item path="userName" label="账号">
            <n-input
              v-model:value="formValue.userName"
              placeholder="请输入账号"
              size="large"
              class="input-clean"
              :loading="loading"
              autocomplete="username"
              data-testid="username-input"
            />
          </n-form-item>

          <n-form-item path="password" label="密码">
            <n-input
              type="password"
              v-model:value="formValue.password"
              placeholder="请输入密码"
              size="large"
              class="input-clean"
              :loading="loading"
              showPasswordOn="click"
              autocomplete="current-password"
              data-testid="password-input"
            />
          </n-form-item>

          <n-button
            type="primary"
            size="large"
            class="w-full h-12 rounded-lg shadow-sm hover:shadow transition-shadow"
            @click="handleLogin"
            :loading="loading"
          >
            立即登录
          </n-button>
        </n-form>

        <!-- 注册表单 -->
        <n-form
          v-else
          ref="formRegisterRef"
          :model="formValue"
          :rules="registerRule"
          class="space-y-6"
          key="register"
        >
          <n-form-item path="userName" label="账号">
            <n-input
              v-model:value="formValue.userName"
              placeholder="请输入账号"
              size="large"
              class="input-clean"
              :loading="loading"
              autocomplete="new-username"
              data-testid="reg-username-input"
            />
          </n-form-item>

          <n-form-item path="phone" label="手机号">
            <n-input
              v-model:value="formValue.phone"
              placeholder="请输入手机号"
              size="large"
              class="input-clean"
              :loading="loading"
              autocomplete="new-tel"
              data-testid="phone-input"
            />
          </n-form-item>

          <n-form-item path="password" label="密码">
            <n-input
              type="password"
              v-model:value="formValue.password"
              placeholder="请输入密码"
              size="large"
              class="input-clean"
              :loading="loading"
              showPasswordOn="click"
              autocomplete="new-password"
              data-testid="reg-password-input"
            />
          </n-form-item>

          <n-button
            type="primary"
            size="large"
            class="w-full h-12 rounded-lg shadow-sm hover:shadow transition-shadow"
            @click="handleRegister"
            :loading="loading"
          >
            立即注册
          </n-button>
        </n-form>
      </transition>
    </n-card>
  </div>
</template>

<style scoped>
/* 修复自动填充样式 */
:deep(.n-input input:-webkit-autofill),
:deep(.n-input input:-webkit-autofill:hover),
:deep(.n-input input:-webkit-autofill:focus) {
  -webkit-box-shadow: 0 0 0 1000px white inset !important;
  -webkit-text-fill-color: #303133 !important;
  caret-color: #303133 !important;
  transition: background-color 5000s ease-in-out 0s;
}

.input-clean {
  border-radius: 8px !important;
  border: 1px solid #e4e7ed !important;
  transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
  background: white !important;
}

.input-clean.n-input--focus {
  border-color: #409eff !important;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1) !important;
}

/* 切换动画 */
.fade-slide-enter-active,
.fade-slide-leave-active {
  transition:
    opacity 0.2s ease,
    transform 0.25s cubic-bezier(0.4, 0, 0.2, 1);
}

.fade-slide-enter-from {
  opacity: 0;
  transform: translateY(-10px);
}

.fade-slide-leave-to {
  opacity: 0;
  transform: translateY(10px);
}

/* 按钮悬停效果 */
.n-button:not(.n-button--disabled):hover {
  transform: translateY(-1px);
  transition: all 0.2s ease;
}

/* 卡片样式 */
.n-card {
  background: white;
  border: 1px solid #f0f0f0;
  box-shadow: 0 6px 16px -8px rgba(0, 0, 0, 0.08),
  0 9px 28px 0 rgba(0, 0, 0, 0.05),
  0 12px 48px 16px rgba(0, 0, 0, 0.03) !important;
}
</style>
